<%@page import="ChatRoom.*" %>
<%@page import="java.util.*" %>
<%@page import="java.text.DateFormat" %>
<% 
String userName = request.getParameter("username");
if(userName == null) {
	response.sendRedirect("./");
}
String text = null;
Long startTime = null;
try {
	text = request.getParameter("text");
	startTime = Long.valueOf(request.getParameter("starttime"));
} catch (Exception e) {}
if (text != null) {
	chatlog log = new chatlog(userName, System.currentTimeMillis(), text);
	chatRoomFacade.update(log);
}
if (startTime == null) {
	startTime = System.currentTimeMillis();
}
List<chatlog> history = new ArrayList<chatlog>();
try {
	if (userName != null && startTime != null) {
		history = chatRoomFacade.getRecent(userName, startTime);
	}
} catch (Exception e) {out.println(e);}
%>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link charset="utf-8" media="screen" type="text/css" href="css/style.css" rel="stylesheet" />
<script type="text/javascript">
window.onload = function(){
	var obj = document.getElementById("history");
	obj.scrollTop = obj.scrollHeight;
};
</script>
<title>ChatRoom</title>
</head>
<body>
<div id="page">
	<div id="header"><a href="/">ChatRoom</a></div>
	<div id="content">
		Welcome <% out.println(userName); %>
		<div id="history">
			<ul>
<% for (chatlog log : history) { %>
				<li><% out.print("[" + DateFormat.getInstance().format(new Date(log.getTimestamp())) + "] <b>" + log.getUsername() + "</b> : " + log.getText()); %></li>
<% } %>
			</ul>
		</div>
		<div id="inputarea">
			<form method="post" method="post" action="main.jsp">
				<input type="hidden" name="username" value="<% out.print(userName); %>" />
<% if(startTime != null) { %>
				<input type="hidden" name="starttime" value="<% out.print(startTime); %>" />
<% } %>
				<input id="text" name="text" type="text" size="40px" /> 
				<input value="Send" type="submit" />
			</form>
		</div>
	</div>
	<div id="footer"></div>
</div>
</body>
</html>